import * as echarts from "echarts";
// import empty from "@/assets/svg/empty.svg";

export const energyNameMap = {
  null: null,
  electricity: "电(KVA)",
  running: "自来水(m³)",
  reclaim: "再生水(m³)",
  ng: "天然气(Nm³)",
  steam: "蒸汽(t)",
  hot: "热水(GJ)",
  cda: "CDA/IA(Nm³)",
  hpcda: "HPCDA(Nm³)",
  xcda: "XCDA(Nm³)",
  n2: "N₂(Nm³)",
  h2: "H₂(Nm³)",
  o2: "O₂(Nm³)",
  ar: "Ar(Nm³)",
  he: "He(Nm³)",
  co2: "CO₂(Nm³)"
};

export const customColorProgress = val => {
  if (val < 26) {
    return "#39C670";
  } else if (val >= 26 && val <= 50) {
    return "#FFCA45";
  } else if (val >= 51 && val <= 75) {
    return "#FF8443";
  } else {
    return "#FF4500";
  }
};

export const lineAreaColor = [
  {
    start: "rgba(74,143,255,0)",
    end: "rgba(74,143,255,0.35)"
  },
  {
    start: "rgba(123,203,255,0)",
    end: "rgba(123,203,255,0.35)"
  },
  {
    start: "rgba(204,161,81,0)",
    end: "rgba(204,161,81,0.35)"
  },
  {
    start: "rgba(204,195,81,0)",
    end: "rgba(204,195,81,0.35)"
  },
  {
    start: "rgba(70,209,115,0)",
    end: "rgba(70,209,115,0.35)"
  },
  {
    start: "rgba(167,96,215,0)",
    end: "rgba(167,96,215,0.35)"
  },
  {
    start: "rgba(204,107,113,0)",
    end: "rgba(204,107,113,0.35)"
  }
];

export const drawEmptyChart = (subtext = "No Data") => {
  return {
    title: {
      text: " {a|}",
      x: "center",
      y: "center",
      subtext,
      itemGap: -20,
      textStyle: {
        rich: {
          a: {
            fontSize: 13,
            height: 100
            // backgroundColor: {
            //   image: empty
            // }
          }
        }
      },
      subtextStyle: {
        color: "#909399",
        fontSize: 13
      }
    }
  };
};

// 基础折线图
export const drawLineChart = (dom, xData = [], yData = [], legendData = [], unit = "", color = "black") => {
  let myChart = echarts.init(dom);
  let option = {};
  if (xData.length === 0 || yData.length === 0) {
    option = drawEmptyChart();
  } else {
    option = {
      grid: {
        left: 30,
        right: 20,
        bottom: 20,
        containLabel: true
      },
      tooltip: {
        trigger: "axis"
      },
      legend: {
        data: legendData,
        top: 25,
        textStyle: {
          color: color
        }
      },
      xAxis: {
        type: "category",
        boundaryGap: false,
        data: xData
      },
      yAxis: {
        type: "value",
        name: unit,
        splitLine: {
          show: true,
          lineStyle: {
            type: "dashed",
            color: "rgba(187, 226, 255, .3)"
          }
        },
        axisLine: {
          show: true
        },
        axisLabel: {
          formatter: function (value) {
            if (value >= 1000000000) {
              return (value / 1000000000).toFixed(1) + "B"; // 十亿
            } else if (value >= 1000000) {
              return (value / 1000000).toFixed(1) + "M"; // 百万
            } else if (value >= 1000) {
              return (value / 1000).toFixed(1) + "K"; // 千
            }
            return value; // 原始值
          }
        }
      },
      series: [
        {
          name: legendData[0],
          data: yData,
          type: "line",
          smooth: true,
          areaStyle: {
            color: {
              type: "linear",
              x: 0,
              y: 0,
              x2: 0,
              y2: 1,
              colorStops: [
                {
                  offset: 0,
                  color: "rgba(74,143,255,0.35)" // 100% 处的颜色
                },
                {
                  offset: 1,
                  color: "rgba(74,143,255,0)" // 0% 处的颜色
                }
              ],
              global: false // 缺省为 false
            }
          }
        }
      ]
    };
  }
  myChart.resize();
  option && myChart.setOption(option);
};

// 堆叠折线图
export const drawMultiLineChart = (dom, xData = [], series = [], legendData = [], unit = "", color = "black") => {
  let myChart = echarts.init(dom);

  let option = {};
  if (xData.length === 0 || series.length === 0) {
    option = drawEmptyChart();
  } else {
    option = {
      grid: {
        left: 30,
        right: 20,
        bottom: 20,
        containLabel: true
      },
      tooltip: {
        trigger: "axis"
      },
      legend: {
        type: "scroll",
        top: 25,
        left: legendData?.length > 2 ? 100 : "center",
        data: legendData,
        textStyle: {
          color: color
        }
      },
      xAxis: [
        {
          type: "category",
          boundaryGap: false,
          data: xData
        }
      ],
      yAxis: [
        {
          type: "value",
          name: unit,
          splitLine: {
            show: true,
            lineStyle: {
              type: "dashed",
              color: "rgba(187, 226, 255, .3)"
            }
          },
          axisLine: {
            show: true
          },
          axisLabel: {
            formatter: function (value) {
              if (value >= 1000000000) {
                return (value / 1000000000).toFixed(1) + "B"; // 十亿
              } else if (value >= 1000000) {
                return (value / 1000000).toFixed(1) + "M"; // 百万
              } else if (value >= 1000) {
                return (value / 1000).toFixed(1) + "K"; // 千
              }
              return value; // 原始值
            }
          }
        }
      ],
      series: series
    };
  }
  myChart.resize();
  option && myChart.setOption(option);
};

// 柱状图
export const drawBarChart = (dom, xData = [], yData = [], legendData = [], unit = "", color = "black") => {
  let myChart = echarts.init(dom);
  let option = {};
  if (xData.length === 0 || yData.length === 0) {
    option = drawEmptyChart();
  } else {
    option = {
      grid: {
        left: 30,
        right: 20,
        bottom: 20,
        containLabel: true
      },
      tooltip: {
        trigger: "axis",
        formatter: function (params) {
          // let total = 0;
          // // 蒸汽/热水块，只需要合计GJ类型的数据
          // let paramsGj = params.filter(item => item.seriesName.includes("GJ"));
          // if (paramsGj.length) {
          //   total = paramsGj.reduce((sum, item) => {
          //     item.value = item.value ? item.value : 0;
          //     return sum + Number(item.value);
          //   }, 0);
          // } else {
          //   total = params.reduce((sum, item) => {
          //     item.value = item.value ? item.value : 0;
          //     return sum + Number(item.value);
          //   }, 0);
          // }
          // total = total.toFixed(2);
          // 生成内容
          let html = `<div>${params[0].name}</div>`;
          params.forEach(item => {
            html += `<div style="display: flex;align-items: center"><div style="width: 10px;height: 10px;background-color: ${item.color};border-radius: 50%"></div>&nbsp;<div style="flex: 1">${item.seriesName}</div>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<div style="font-weight: bold;">${item.value ? item.value : "-"}</div></div>`;
          });
          // html += `<div style="display: flex"><span style="flex-grow: 1; margin-left: 14px">合计</span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="font-weight: bold;float: right">${total}</span></d>`;
          return html;
        }
      },
      legend: {
        data: legendData,
        top: 25,
        textStyle: {
          color: color
        }
      },
      xAxis: {
        type: "category",
        boundaryGap: false,
        data: xData
      },
      yAxis: {
        type: "value",
        name: unit,
        splitLine: {
          show: true,
          lineStyle: {
            type: "dashed",
            color: "rgba(187, 226, 255, .3)"
          }
        },
        axisLine: {
          show: true
        },
        axisLabel: {
          formatter: function (value) {
            if (value >= 1000000000) {
              return (value / 1000000000).toFixed(1) + "B"; // 十亿
            } else if (value >= 1000000) {
              return (value / 1000000).toFixed(1) + "M"; // 百万
            } else if (value >= 1000) {
              return (value / 1000).toFixed(1) + "K"; // 千
            }
            return value; // 原始值
          }
        }
      },
      series: [
        {
          name: legendData[0],
          data: yData,
          type: "bar",
          smooth: true,
          areaStyle: {
            color: {
              type: "linear",
              x: 0,
              y: 0,
              x2: 0,
              y2: 1,
              colorStops: [
                {
                  offset: 0,
                  color: "rgba(74,143,255,0.35)" // 100% 处的颜色
                },
                {
                  offset: 1,
                  color: "rgba(74,143,255,0)" // 0% 处的颜色
                }
              ],
              global: false // 缺省为 false
            }
          }
        }
      ]
    };
  }
  myChart.resize();
  option && myChart.setOption(option);
};

// 堆叠柱状图
export const drawStackedBarChart = (dom, xData = [], series = [], legendData = [], unit = "", color = "black") => {
  let myChart = echarts.init(dom);

  let option = {};
  if (xData.length === 0 || series.length === 0) {
    option = drawEmptyChart();
  } else {
    option = {
      grid: {
        left: 30,
        right: 20,
        bottom: 20,
        containLabel: true
      },
      tooltip: {
        trigger: "axis",
        formatter: function (params) {
          let total = 0;
          // 蒸汽/热水块，只需要合计GJ类型的数据
          let paramsGj = params.filter(item => item.seriesName.includes("GJ"));
          if (paramsGj.length) {
            total = paramsGj.reduce((sum, item) => {
              item.value = item.value ? item.value : 0;
              return sum + Number(item.value);
            }, 0);
          } else {
            total = params.reduce((sum, item) => {
              item.value = item.value ? item.value : 0;
              return sum + Number(item.value);
            }, 0);
          }
          total = total.toFixed(2);
          // 生成内容
          let html = `<div>${params[0].name}</div>`;
          params.forEach(item => {
            html += `<div style="display: flex;align-items: center"><div style="width: 10px;height: 10px;background-color: ${item.color};border-radius: 50%"></div>&nbsp;<div style="flex: 1">${item.seriesName}</div>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<div style="font-weight: bold;">${item.value ? item.value : "-"}</div></div>`;
          });
          // 如果是大宗气，则不展示合计
          if (unit === "Nm³") {
            return html;
          }
          html += `<div style="display: flex"><span style="flex-grow: 1; margin-left: 14px">合计</span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="font-weight: bold;float: right">${total}</span></d>`;
          return html;
        }
      },
      legend: {
        type: "scroll",
        top: 25,
        left: legendData?.length > 2 ? 100 : "center",
        data: legendData,
        textStyle: {
          color: color
        }
      },
      xAxis: [
        {
          type: "category",
          boundaryGap: false,
          data: xData
        }
      ],
      yAxis: [
        {
          type: "value",
          name: unit,
          splitLine: {
            show: true,
            lineStyle: {
              type: "dashed",
              color: "rgba(187, 226, 255, .3)"
            }
          },
          axisLine: {
            show: true
          },
          axisLabel: {
            formatter: function (value) {
              if (value >= 1000000000) {
                return (value / 1000000000).toFixed(1) + "B"; // 十亿
              } else if (value >= 1000000) {
                return (value / 1000000).toFixed(1) + "M"; // 百万
              } else if (value >= 1000) {
                return (value / 1000).toFixed(1) + "K"; // 千
              }
              return value; // 原始值
            }
          }
        }
      ],
      series: series
    };
  }
  myChart.resize();
  option && myChart.setOption(option);
};

/**
 * 金额格式化
 * num：格式化目标数字
 * decimal：保留几位小数，默认2位
 * split：千分位分隔符，默认为,
 * moneyFormat(123456789.87654321, 2, ',') // 123,456,789.88
 */
export const moneyFormat = (num, decimal = 2, split = ",") => {
  if (num === null || num === undefined) {
    return "--";
  }
  const thousandFormat = num => {
    const len = num.length;
    return len <= 3 ? num : thousandFormat(num.substr(0, len - 3)) + split + num.substr(len - 3, 3);
  };
  if (isFinite(num)) {
    // num是数字
    if (num === 0) {
      // 为0
      return num.toFixed(decimal);
    } else {
      // 非0
      var res = "";
      var dotIndex = String(num).indexOf(".");
      if (dotIndex === -1) {
        // 整数
        res = thousandFormat(String(num)) + "." + "0".repeat(decimal);
      } else {
        // 非整数
        // js四舍五入 Math.round()：正数时4舍5入，负数时5舍6入
        // Math.round(1.5) = 2
        // Math.round(-1.5) = -1
        // Math.round(-1.6) = -2
        // 保留decimals位小数
        const numStr = String((Math.round(num * Math.pow(10, decimal)) / Math.pow(10, decimal)).toFixed(decimal)); // 四舍五入，然后固定保留2位小数
        const decimals = numStr.slice(dotIndex, dotIndex + decimal + 1); // 截取小数位
        res = thousandFormat(numStr.slice(0, dotIndex)) + decimals;
      }
      return res;
    }
  } else {
    return "--";
  }
};

// 计算同比
export const getYearOnYear = (value, lastYearValue) => {
  if ([null, undefined, "--"].includes(value)) {
    return "--";
  }
  if ([null, undefined, "--", 0, "0.00"].includes(lastYearValue)) {
    return "--";
  }
  return (((value - lastYearValue) / lastYearValue) * 100).toFixed(2) + "%";
};

// 计算两个数相除
export const getQuotient = (value1, value2) => {
  if ([null, undefined].includes(value1)) {
    return "--";
  }
  if ([null, undefined, 0, "0.00"].includes(value2)) {
    return "--";
  }
  return (value1 / value2).toFixed(2);
};
